package com.example.auth.service.impl;

import com.example.auth.dao.ClientRepository;
import com.example.auth.dao.ClientServiceRepository;
import com.example.auth.dao.mongdb.MongoClientRepository;
import com.example.auth.model.SysClient;
import com.example.auth.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by wangtao on 2018/3/6.
 */
@Service
public class ClientServiceImpl implements ClientService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private ClientRepository clientRepository;
    @Autowired
    private ClientServiceRepository clientServiceRepository;
    @Autowired
    private MongoClientRepository mongoClientRepository;

    @Override
    public SysClient findOne(Long id) {
        return clientRepository.findOne(id);
    }

    @Override
    public SysClient findByCode(String code) {
        return clientRepository.findByCode(code);
    }

    @Override
    public List<String> findAllService(Long clientId) {
        StringBuilder sb = new StringBuilder("select `code` from sys_client where id in(");
        sb.append("select scs.service_id from sys_client sc,sys_client_service scs where sc.id = scs.client_id and sc.id = " + clientId);
        sb.append(")");
        Query query = entityManager.createNativeQuery(sb.toString());
        return query.getResultList();
    }

    @Override
    public void synClientCache() {
        List<SysClient> list = clientRepository.findAll();
        if(!list.isEmpty()){
            mongoClientRepository.save(list);
        }
    }
}
